package com.mlnx.transport.service;

import com.mlnx.common.utils.MyLog;
import com.mlnx.data.entity.EcgInfo;
import com.mlnx.device.pojo.dto.DeviceStateRecord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by amanda.shan on 2020/3/19.
 */
@Service
public class DataTransportService {

    private MyLog log = MyLog.getLog(getClass());

    @Autowired
    @Qualifier("template106")
    private MongoTemplate template106;

    @Autowired
    @Qualifier("templateAli")
    private MongoTemplate templateAli;

    private boolean synEcgDataFlag = false;

    public void transDeviceStateRecord() {

        int index = 0;
        while (true) {
            Query query = new Query().skip(index).limit(100);

            List<DeviceStateRecord> deviceStateRecords = template106.find(query, DeviceStateRecord.class,
                    "device_collection");

            if (deviceStateRecords != null && deviceStateRecords.size() > 0) {
                for (DeviceStateRecord deviceStateRecord : deviceStateRecords) {
                    try {
                        templateAli.save(deviceStateRecord, "device_collection");
                    } catch (DuplicateKeyException e) {
                        log.error("重复数据{}", deviceStateRecord);
                    }
                }
                index += 10;
                log.info("备份{}", index);
            } else {
                break;
            }
        }
    }

    public void startSynEcg(Integer patientId, final Long startTime, Integer limit) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                synEcg(patientId, startTime, limit);
            }
        }).start();

    }

    public void startMutilSynEcg(Integer startPatientId, Integer endPatientId, final Long startTime, Integer limit) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                synEcgDataFlag = true;
                for (int i = startPatientId; i <= endPatientId; i++) {
                    if (synEcgDataFlag){
                        synEcg(i, startTime, limit);
                    }
                }
            }
        }).start();

    }

    private void synEcg(Integer patientId, final Long startTime, Integer limit) {
        Long recordTime = startTime;

        Criteria criteria = Criteria.where("patientId").is(patientId);
        criteria.and("startTime").gte(recordTime);
        Query query = Query.query(criteria);
        long count = template106.count(query, "ecg_collection");
        log.info("{} 心电数据总数 {}", patientId, count);


        synEcgDataFlag = true;
        while (synEcgDataFlag) {
            criteria = Criteria.where("patientId").is(patientId);
            criteria.and("startTime").gt(recordTime);
            query = Query.query(criteria).limit(limit).with(new Sort(Sort.Direction.ASC, "startTime"));

            List<EcgInfo> ecgInfos = null;
            try {
                ecgInfos = template106.find(query, EcgInfo.class,
                        "ecg_collection");
            } catch (Exception e) {
                log.error(e, "读取106异常");
            }

            if (ecgInfos != null && ecgInfos.size() > 0) {
                log.info("{} 备份{}", patientId,
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(recordTime)));

                for (int i = 0; i < ecgInfos.size(); i++) {
                    ecgInfos.get(i).setData(null);
                }

                try {
                    templateAli.insert(ecgInfos, "ecg_collection");
                    recordTime = ecgInfos.get(ecgInfos.size() - 1).getStartTime();
                } catch (DuplicateKeyException e) {
                    log.error("重复数据");
                    recordTime = ecgInfos.get(ecgInfos.size() - 1).getStartTime();
                } catch (Exception e) {
                    log.error(e, "{} 保存心电异常异常", patientId);
                }
            } else {
                break;
            }
        }
        log.info("{} 结束备份", patientId);
    }

    public void stopSynEcg() {
        synEcgDataFlag = false;
    }
}
